//
//  Game_CenterViewController.m
//  Game Center
//
//  Copyright BooLooLeeLoo Studio. All rights reserved.
//

#import "LittleBallGameCenterViewController.h"
#import "AppSpecificValues.h"
#import "GameCenterManager.h"

@implementation LittleBallGameCenterViewController

@synthesize gameCenterManager;
@synthesize currentScore;
@synthesize currentLeaderBoard;
@synthesize currentScoreLabel;
@synthesize storedScores, storedScoresFilename;


- (void)dealloc
{
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.currentLeaderBoard = @"1"; //kLeaderboardID;
	self.currentScore = 10;
    
    currentScoreLabel.text = [NSString stringWithFormat: @"%ld", self.currentScore];
    
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    storedScoresFilename = [[NSString alloc] initWithFormat:@"%@/%@.storedScores.plist",path,[GKLocalPlayer localPlayer].playerID];
    writeLock = [[NSLock alloc] init];
	
    
	if ([GameCenterManager isGameCenterAvailable]) {
		
		self.gameCenterManager = [[GameCenterManager alloc] init] ;
		[self.gameCenterManager setDelegate:self];
		[self.gameCenterManager authenticateLocalUser];
		
		
	} else {
		
		//...... TBD
	}
}


//******************************************
// 排行榜
//******************************************
- (IBAction) showLeaderboard
{
	GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
	if (leaderboardController != NULL) 
	{
		leaderboardController.category = self.currentLeaderBoard;
		leaderboardController.timeScope = GKLeaderboardTimeScopeWeek;
		leaderboardController.leaderboardDelegate = self; 
		[self presentModalViewController: leaderboardController animated: YES];
	}
    
    
    GKScore * Score = [[GKScore alloc] initWithCategory:currentLeaderBoard];
    [Score setValue:currentScore]; 
    [Score setShouldSetDefaultLeaderboard:YES];
    
    if(self.currentScore > 0)
    {
        [self submitScore:Score];
    }
}


// 提交分数
- (void)submitScore:(GKScore *)score 
{
    if ([GKLocalPlayer localPlayer].authenticated) {
        if (!score.value) {
            return;
        }
        [score reportScoreWithCompletionHandler:^(NSError *error){
            if (!error || (![error code] && ![error domain])) {
                //[self resubmitStoredScores];
            } else {
                //[self storeScore:score];
            }
        }];
    } 
}


// 重新提交分数
- (void)resubmitStoredScores
{
    if (storedScores) {
        int index = [storedScores count]-1;
        while( index >= 0 ) {
            GKScore * score = [storedScores objectAtIndex:index];
            [self submitScore:score];
            [storedScores removeObjectAtIndex:index];
            index--;
        }
        [self writeStoredScore];
    }
}

// 从本地读取分数
- (void)loadStoredScores
{
    NSArray *  unarchivedObj = [NSKeyedUnarchiver unarchiveObjectWithFile:storedScoresFilename];
    
    if (unarchivedObj) {
        storedScores = [[NSMutableArray alloc] initWithArray:unarchivedObj];
        [self resubmitStoredScores];
    } else {
        storedScores = [[NSMutableArray alloc] init];
    }
}



// 保存分数到文件 
- (void)writeStoredScore
{
    [writeLock lock];
    NSData * archivedScore = [NSKeyedArchiver archivedDataWithRootObject:storedScores];
    NSError * error;
    [archivedScore writeToFile:storedScoresFilename options:NSDataWritingFileProtectionNone error:&error];
    if (error) {
        NSLog(@"文件保存出错!!");
    }
    [writeLock unlock];
}



// 存储分数以备后用
- (void)storeScore:(GKScore *)score 
{
    [storedScores addObject:score];
    [self writeStoredScore];
}



- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
	[self dismissModalViewControllerAnimated: YES];
}





//******************************************
// 成就榜
//******************************************
- (IBAction) showAchievements
{

    GKAchievementViewController *achievements = [[GKAchievementViewController alloc] init];
	if (achievements != NULL)
	{
		achievements.achievementDelegate = self;
		[self presentModalViewController: achievements animated: YES];
	}
      
    [self checkAchievements];
    
}


- (void)achievementViewControllerDidFinish:(GKAchievementViewController *)viewController;
{
	[self dismissModalViewControllerAnimated: YES];
}

- (void) checkAchievements
{
    identifier = nil;
    achievementsPercentageComplete = 0;
    
    
    // 不同称号范围（对应不同成就ID）
    if (currentScore < 5)
    {
        identifier = @"com.boolooleeloo.lb.1";
        achievementsPercentageComplete = 100.0;
    }
    else 
    {
        if (currentScore < 15) 
        {
            identifier = @"com.boolooleeloo.lb.2";
            achievementsPercentageComplete = 100.0;
        }
        else 
        {
            if (currentScore < 30) {
                identifier = @"com.boolooleeloo.lb.3";
                achievementsPercentageComplete = 100.0;
            }
        }
    }
    
    if(identifier != nil)
    {
        GKAchievement * achievement = [[GKAchievement alloc] initWithIdentifier:identifier];
        //[self.gameCenterManager submitAchievement: identifier percentComplete: percentComplete];
            
        [achievement setPercentComplete: achievementsPercentageComplete];
        [self submitAchievement:achievement];
    }
}


- (void)submitAchievement:(GKAchievement *)achievement 
{
    if (achievement) {
        [achievement reportAchievementWithCompletionHandler: ^(NSError *error){
            if (error) {
                UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"您的网络不正常"
                                                                         delegate:self
                                                                cancelButtonTitle:@"取消" 
                                                           destructiveButtonTitle:@"离开" 
                                                                otherButtonTitles:nil];
                [actionSheet showInView:[self view]];
            } else {
            //
            }
        }];
    }
}


- (IBAction) reset
{
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"您确定要重置分数和成就吗?"
															 delegate:self
													cancelButtonTitle:@"取消" 
											   destructiveButtonTitle:@"重置" 
													otherButtonTitles:nil];
	[actionSheet showInView:[self view]];
	
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0) {
		
		[gameCenterManager resetAchievements];
		
		self.currentScore = 0;
		currentScoreLabel.text = [NSString stringWithFormat: @"%ld", self.currentScore];
        
	}
}

- (IBAction) backToFatherView:(id)sender
{
    [self.view removeFromSuperview];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    
    self.gameCenterManager = nil;
	self.currentLeaderBoard = nil;
	self.currentScoreLabel = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
